#!/bin/bash
# set -e # 建议在调试完成后开启

# color
source /etc/init.d/functions
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

# --- 函数定义 ---

# 历史命令审计
function historyConf(){
    #echo "--> Configuring command history auditing"
    local profile_file="/etc/profile"
    # 使用唯一的注释标记来判断是否已配置
    if ! grep -q "# CUSTOM_HISTORY_AUDIT" "$profile_file"; then
        cat >> "$profile_file" << \EOF

# CUSTOM_HISTORY_AUDIT - Log user commands
export HISTTIMEFORMAT="[%F %T] "
export PROMPT_COMMAND='
if [ -n "$BASH" ]; then
    # Get user, tty, ip, and pwd
    USER_INFO=$(who am i | awk "{print \"user=[\" \$1 \"] tty=[\" \$2 \"] date=[\" \$3 \" \" \$4 \"] ip=[\" \$5 \"]\"}")
    [ -z "$USER_INFO" ] && USER_INFO="user=[$(whoami)]"
    
    # Get the last command from history
    LAST_CMD=$(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//")
    
    # Log to file
    echo "$(date "+%F %T") ${USER_INFO} pwd=[$(pwd)] cmd=[${LAST_CMD}]" >> /var/log/usercmd.log
fi
'
EOF
        # 创建日志文件并设置安全权限 (640: root读写, root组读)
        # 更好的方案是配合 logrotate 和 ACL
        touch /var/log/usercmd.log
        chmod 622 /var/log/usercmd.log
        #echo "History audit enabled. Log file: /var/log/usercmd.log"
    else
        echo -e "${yellow}Warn:${plain} History audit seems to be already configured. Skipping."
    fi
}

# 时间同步配置
function chronyConf(){
    #echo "--> Configuring Chrony to use Aliyun NTP servers"
    local conf_file="/etc/chrony.conf"
    # 更健壮的修改方式：注释所有 server/pool，然后添加新的
    sed -i -e 's/^\(server .*\)/#\1/g' -e 's/^\(pool .*\)/#\1/g' "$conf_file"
    
    # 检查是否已添加阿里云NTP
    if ! grep -q "ntp.aliyun.com" "$conf_file"; then
        cat >> "$conf_file" << EOF

# Use Aliyun NTP servers - Added by init script
pool ntp.aliyun.com iburst
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst
server ntp3.aliyun.com iburst
EOF
    fi
    
    if systemctl is-active --quiet chronyd; then
        systemctl restart chronyd > /dev/null 2>&1
    else
        systemctl enable --now chronyd > /dev/null 2>&1
    fi
    #echo "Chrony service configured and started."
}

# 基础安全配置（禁用项）
function securityConf(){
    # echo "--> Disabling SELinux and Firewalld"
    # 禁用 SELinux
    if [ "$(getenforce)" != "Disabled" ]; then
        sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
        setenforce 0
        # echo -e "${green}SELinux has been disabled. A reboot is required for it to take full effect.${plain}"
    else
        echo "SELinux is already disabled." > /dev/null
    fi
    
    # 禁用 Firewalld
    if systemctl is-active --quiet firewalld; then
        systemctl stop firewalld
        systemctl disable firewalld
        echo -e "${red}Warning: Firewalld service has been stopped and disabled!${plain}"
    else
        echo "Firewalld is not active." > /dev/null
    fi
}

# 个性化与系统调整
function personConf(){
    # echo "--> Applying personal and system customizations"
    
    # 关闭 Swap
    if [ "$(swapon -s | wc -l)" -gt 1 ]; then
        swapoff -a
        sed -i '/swap/s/^/#/' /etc/fstab
        # echo "Swap has been disabled."
    fi

    # 确保 rc.local 可执行
    chmod +x /etc/rc.d/rc.local

    # 清空登录欢迎信息
    if [ -s /etc/issue ]; then
        cp /etc/issue /etc/issue.bak
        truncate -s 0 /etc/issue
        # echo "/etc/issue cleared. Original backed up to /etc/issue.bak"
    fi
    
    # 设置时区
    timedatectl set-timezone "Asia/Shanghai"
    # echo "Timezone set to Asia/Shanghai."

    # 调整 logrotate
    sed -i 's/^\(rotate \).*/\16/' /etc/logrotate.conf
    # echo "Logrotate 'rotate' count set to 6."
    
    # 禁用 Ctrl-Alt-Del 重启 (正确的方式)
    if [ ! -L /etc/systemd/system/ctrl-alt-del.target ]; then
        systemctl mask ctrl-alt-del.target
        # echo "Ctrl-Alt-Del reboot target has been masked."
    fi
    
    # 配置 root 用户的 vim
    cat > /root/.vimrc << EOF
" Vim settings for root
set ts=4
set expandtab
set shiftwidth=4
set autoindent
set paste
EOF
    # echo "Root's .vimrc has been configured."

    # 配置linux.sh
    cat > /etc/profile.d/linux.sh << \EOF
alias s='ss -nlpt| grep'
alias nel='netstat -anltp|grep LISTEN'

alias dh='df -lht `grep -vE "^#|swap|cdrom|^$" /etc/fstab |awk "{if (\\$2==\"/\") print \\$3}"`'
alias dk="du -sh -- * | sort -rn  | perl -e 'sub h{%h=(K=>10,M=>20,G=>30);(\$n,\$u)=shift=~/([0-9.]+)(\D)/;return \$n*2**\$h{\$u}}print reverse sort{h(\$b)<=>h(\$a)}<>;'"

alias ipa='for i in `ip link |grep -v "link" |awk -F ":" "{print \\$2}"|awk -F "@" "{print \\$1}"`;do iipp=`ip a show $i|grep " inet "|awk  "{print \\$2}"|tr "\n" "|"`;if test "$iipp";then  printf "%-18s%8s\n" "$i" "$iipp"|sed "s/|/ /g"; fi;done |sed "s#/[0-9]*[0-9]##g"'

IP=$(ip addr show eth0 | grep -w "inet" | awk '{ print $2; }' | sed 's/\/.*$//')
export PS1="[\u@\h_\[\e[32m\]$IP\[\e[m\] \w]\\$ "
EOF
    # echo "linux.sh has been configured."

}

# --- 主逻辑 ---
function deal(){
    historyConf
    chronyConf
    securityConf
    personConf
}

function main(){
    action "$0" deal
    #echo -e "\n${green}Initialization script finished.${plain}"
    #echo -e "${yellow}Please note that a reboot is required for some changes (like SELinux) to take full effect.${plain}"
}

main "$@"